//
//  BookDetailViewController.m
//  HuiKaoClient
//
//  Created by Wang Li on 13-2-26.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "BookDetailViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "AppDelegate.h"
#import "asyncimageview.h"
#import "ChartViewController.h"
#import "MyOrderViewController.h"
#import "MainTabBarController.h"
#import "LoginViewController.h"
#import "ComListViewController.h"
#import "WriteDDViewController.h"
#define ImgH 160
@interface BookDetailViewController ()

@end

@implementation BookDetailViewController
@synthesize m_BookIDStr;
- (id)init
{
    if (self =[super init]) {
        // Custom initialization
    }
    return self;
}
-(void) dealloc
{
    [_SendPrice release];
    [_ScrollView release];
    [m_BookIDStr release];
    [_RightBtt release];
    [_BuysBtt release];
    [_NavBtt release];
    [m_titleBttBarItem release];
    [super dealloc];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
//    UILabel* tNavTitleLab = (UILabel*)[self.navigationController.navigationBar viewWithTag:144];
//    [tNavTitleLab setText:@"图书商城"];
    
    m_titleBttBarItem = [[MainTabBarController setTitle:@"图书商城"] retain];
    
    _NavBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_NavBtt setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [_NavBtt addTarget:self action:@selector(navPopPressed) forControlEvents:UIControlEventTouchUpInside];
    _NavBtt.frame =CGRectMake(4, 7, 50, 30);
    [_NavBtt retain];
    UILabel* tBackLab = [[UILabel alloc] initWithFrame:CGRectMake(14, 5, 30, 20)];
    [tBackLab setBackgroundColor:[UIColor clearColor]];
    [tBackLab setTextColor:[UIColor whiteColor]];
    [tBackLab setText:@"返回"];
    [tBackLab setFont:[UIFont systemFontOfSize:13]];
    [_NavBtt addSubview:tBackLab];
    [tBackLab release];
    
    _BuysBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_BuysBtt setImage:[UIImage imageNamed:@"chart.png"] forState:UIControlStateNormal];
    _BuysBtt.frame =CGRectMake(240, 10, 24, 24);
    [_BuysBtt addTarget:self action:@selector(buysBttPressed) forControlEvents:UIControlEventTouchUpInside];
    [_BuysBtt retain];
    
    _RightBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_RightBtt setImage:[UIImage imageNamed:@"orderlist.png"] forState:UIControlStateNormal];
    _RightBtt.frame =CGRectMake(286, 10, 24, 24);
    [_RightBtt addTarget:self action:@selector(orderBttPressed) forControlEvents:UIControlEventTouchUpInside];
    [_RightBtt retain];
    
    _ScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height-44)];
    [_ScrollView setBackgroundColor:[UIColor colorWithRed:245/255.f green:245/255.f blue:245/255.f alpha:1]];
    [self.view addSubview:_ScrollView];
    UIImageView* tImgBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, ImgH)];
    [tImgBG setImage:[UIImage imageNamed:@"book_bg.png"]];
    [_ScrollView addSubview:tImgBG];
    [tImgBG release];
    
    CALayer* tLine0 = [CALayer layer];
    tLine0.frame =CGRectMake(0, 280, 320, 1);
    [tLine0 setBackgroundColor:[UIColor colorWithRed:225/255.f green:224/255.f blue:218/255.f alpha:1].CGColor];
    [_ScrollView.layer addSublayer:tLine0];
    UIButton* tDirectBuyBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [tDirectBuyBtt setImage:[UIImage imageNamed:@"button_yellow.png"] forState:UIControlStateNormal];
    [tDirectBuyBtt addTarget:self action:@selector(directBuyBtt) forControlEvents:UIControlEventTouchUpInside];
    tDirectBuyBtt.frame =CGRectMake(10, tLine0.frame.origin.y+8, 160, 40);
    [_ScrollView addSubview:tDirectBuyBtt];
    UILabel* tBuyLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 160, 20)];
    [tBuyLab setBackgroundColor:[UIColor clearColor]];
    [tBuyLab setText:@"立刻购买"];
    tBuyLab.textAlignment = UITextAlignmentCenter;
    [tBuyLab setTextColor:[UIColor whiteColor]];
    [tBuyLab setFont:[UIFont systemFontOfSize:16]];
    [tDirectBuyBtt addSubview:tBuyLab];
    [tBuyLab release];
    
    UIButton* tOrdBuyBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [tOrdBuyBtt setImage:[UIImage imageNamed:@"button_blue.png"] forState:UIControlStateNormal];
    [tOrdBuyBtt addTarget:self action:@selector(orderBuyBtt) forControlEvents:UIControlEventTouchUpInside];
    tOrdBuyBtt.frame =CGRectMake(180, tLine0.frame.origin.y+8, 130, 40);
    [_ScrollView addSubview:tOrdBuyBtt];
    UILabel* tOrdLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 130, 20)];
    [tOrdLab setBackgroundColor:[UIColor clearColor]];
    [tOrdLab setText:@"放入购物车"];
    tOrdLab.textAlignment = UITextAlignmentCenter;
    [tOrdLab setTextColor:[UIColor whiteColor]];
    [tOrdLab setFont:[UIFont systemFontOfSize:16]];
    [tOrdBuyBtt addSubview:tOrdLab];
    [tOrdLab release];
    
    CALayer* tLine1 = [CALayer layer];
    tLine1.frame =CGRectMake(0, 336, 320, 1);
    [tLine1 setBackgroundColor:[UIColor colorWithRed:225/255.f green:224/255.f blue:218/255.f alpha:1].CGColor];
    [_ScrollView.layer addSublayer:tLine1];
    
    NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getProductDetail&id=%@",RequestCurrentURL,m_BookIDStr];
    [self requestDetailData:tURLStr];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar addSubview:_NavBtt];
    [self.navigationController.navigationBar addSubview:_BuysBtt];
    [self.navigationController.navigationBar addSubview:_RightBtt];
    [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_NavBtt removeFromSuperview];
    [_BuysBtt removeFromSuperview];
    [_RightBtt removeFromSuperview];
    [m_titleBttBarItem removeFromSuperview];
}

-(void) navPopPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) buysBttPressed
{
    ChartViewController* tChartVC = [[ChartViewController alloc] init];
    tChartVC.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tChartVC animated:YES];
    [tChartVC release];
}
-(void) orderBttPressed
{
    MyOrderViewController* iMyOrder = [[MyOrderViewController alloc] init];
    //iMyOrder.hidesBottomBarWhenPushed = YES;
    iMyOrder.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:iMyOrder animated:YES];
    [iMyOrder release];
    
}
//放入购物车
-(void) orderBuyBtt
{
    [self requestAddChartRequest];
}
//直接购买
-(void) directBuyBtt
{
    NSMutableString* tTmpStr = [NSMutableString string];
    NSMutableString* tTmpStr1 = [NSMutableString string];
    WriteDDViewController* tWriteDDVC = [[WriteDDViewController alloc] init];
    tWriteDDVC.m_ProPrice = _SendPrice;
    

    [tTmpStr appendString:@"1"];

        
    [tTmpStr1 appendString:m_BookIDStr];
   
    
    tWriteDDVC.m_ProdNums =tTmpStr;
    tWriteDDVC.m_ProdIDs =tTmpStr1;
    tWriteDDVC.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tWriteDDVC animated:YES];
    [tWriteDDVC release];
}
//显示评论
-(void) toShowCommView
{
    ComListViewController* tComVC = [[ComListViewController alloc] init];
    tComVC.m_ProductID = m_BookIDStr;
    tComVC.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tComVC animated:YES];
    [tComVC release];
}

-(void) requestAddChartRequest
{
    MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;

        [self addHudLoad];
        NSDictionary* tDataDic = [tMainTabController.m_UserDic objectForKey:@"data"];
        NSString* tURLStr = nil;
        if ( tMainTabController.m_UserDic != nil) {
            tURLStr = [NSString stringWithFormat:@"%@ac=addToCart&product_id=%@&cur_user_id=%@&UDID=%@",RequestCurrentURL,m_BookIDStr,[tDataDic objectForKey:@"user_id"],[UIDevice currentDevice].uniqueIdentifier];
        }else{
            tURLStr = [NSString stringWithFormat:@"%@ac=addToCart&product_id=%@&UDID=%@",RequestCurrentURL,m_BookIDStr,[UIDevice currentDevice].uniqueIdentifier];
        }
        ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tURLStr]];
        [tRequestPage setDelegate:self];
        [tRequestPage setDidFailSelector:@selector(requestDetailFail:)];
        [tRequestPage setDidFinishSelector:@selector(requestAddChartFinish:)];
        [tRequestPage startAsynchronous];

}

-(void) requestAddChartFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            if ([[tRealDataDic objectForKey:@"result"] intValue] == 1) {
                [tAppDel showWithCustomView:@"加入购物车成功" detailText:@"" isCue:-1 delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"加入购物车失败" detailText:@"" isCue:-1 delayTime:2];
            }
        }else{
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:-1 delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}

-(void) requestDetailData:(NSString*)f_URLStr
{
    [self addHudLoad];
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:f_URLStr]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestDetailFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestDetailFinish:)];
    [tRequestPage startAsynchronous];
}

-(void) requestDetailFail:(ASIHTTPRequest*)request
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}
-(void) requestDetailFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            UILabel* tTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(10, ImgH+14, 320, 20)];
            [tTitleLab setBackgroundColor:[UIColor clearColor]];
            [tTitleLab setFont:[UIFont boldSystemFontOfSize:18]];
            [tTitleLab setText:[tRealDataDic objectForKey:@"name"]];
            [_ScrollView addSubview:tTitleLab];
            [tTitleLab release];
            
            NSArray* tImgsArr =[tRealDataDic objectForKey:@"image"];
            UIScrollView* tImgsScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 160)];
            [tImgsScroll setBackgroundColor:[UIColor clearColor]];
            tImgsScroll.pagingEnabled = YES;
            tImgsScroll.showsHorizontalScrollIndicator =NO;
            tImgsScroll.showsVerticalScrollIndicator = NO;
            [tImgsScroll setContentSize:CGSizeMake(320*[tImgsArr count], 160)];
            [_ScrollView addSubview:tImgsScroll];
            [tImgsScroll release];
            for (int i=0; i<[tImgsArr count]; i++) {
                NSDictionary* tImgDic = [tImgsArr objectAtIndex:i];
                
                AsyncImageView* tImgView = [[AsyncImageView alloc] initWithFrame:CGRectMake(85+i*320, 5, 150, 150)];
                tImgView.m_BoolSetImage =YES;
                tImgView._numStateRequested =need_Request;
                tImgView._imageRequestURL =tImgDic;
                [tImgsScroll addSubview:tImgView];
                [tImgView customLoadImageFromURL];
                [tImgView release];
            }
            
            NSArray* tInfoArr =[tRealDataDic objectForKey:@"infos"];
            for (int i=0; i<3; i++) {
                NSDictionary* tInfoDic = [tInfoArr objectAtIndex:i];
                UILabel* tDesLab =[[UILabel alloc] initWithFrame:CGRectMake(10, ImgH+38+i*20, 310, 18)];
                [tDesLab setBackgroundColor:[UIColor clearColor]];
                [tDesLab setFont:[UIFont systemFontOfSize:13]];
                [tDesLab setText:[NSString stringWithFormat:@"%@ : %@",[tInfoDic objectForKey:@"name"],[tInfoDic objectForKey:@"data"]]];
                [_ScrollView addSubview:tDesLab];
                [tDesLab release];
            }
            UILabel* tTNLab =[[UILabel alloc] initWithFrame:CGRectMake(10, ImgH+98, 310, 18)];
            [tTNLab setBackgroundColor:[UIColor clearColor]];
            [tTNLab setFont:[UIFont systemFontOfSize:13]];
            [tTNLab setText:@"商城价 : "];
            [_ScrollView addSubview:tTNLab];
            [tTNLab release];
            UILabel* tTNPriceLab =[[UILabel alloc] initWithFrame:CGRectMake(60, ImgH+98, 210, 18)];
            [tTNPriceLab setBackgroundColor:[UIColor clearColor]];
            [tTNPriceLab setFont:[UIFont systemFontOfSize:13]];
            [tTNPriceLab setTextColor:[UIColor colorWithRed:251/255.f green:153/255.f blue:0 alpha:1]];
            _SendPrice = [tRealDataDic objectForKey:@"price"];
            [_SendPrice retain];
            [tTNPriceLab setText:[tRealDataDic objectForKey:@"price"]];
            [_ScrollView addSubview:tTNPriceLab];
            [tTNPriceLab release];
            
            UITextView* tDesTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, 336+8, 310, 10)];
            [tDesTextView setFont:[UIFont systemFontOfSize:14]];
            tDesTextView.userInteractionEnabled =NO;
            [tDesTextView setBackgroundColor:[UIColor clearColor]];
            [tDesTextView setText:[tRealDataDic objectForKey:@"intro"]];
            [_ScrollView addSubview:tDesTextView];
            [tDesTextView release];
            CGRect aframe = tDesTextView.frame;
            aframe.size.height = tDesTextView.contentSize.height;
            tDesTextView.frame = aframe;
            
            
            CALayer* tLine1 = [CALayer layer];
            tLine1.frame =CGRectMake(0, 336+8+tDesTextView.contentSize.height, 320, 1);
            [tLine1 setBackgroundColor:[UIColor colorWithRed:225/255.f green:224/255.f blue:218/255.f alpha:1].CGColor];
            [_ScrollView.layer addSublayer:tLine1];
            
            UILabel* tPJLab = [[UILabel alloc] initWithFrame:CGRectMake(15, 336+8+tDesTextView.contentSize.height+12, 100, 20)];
            [tPJLab setBackgroundColor:[UIColor clearColor]];
            [tPJLab setFont:[UIFont boldSystemFontOfSize:19]];
            [tPJLab setText:@"查看评价"];
            [_ScrollView addSubview:tPJLab];
            [tPJLab release];
            int tStarNum = [[tRealDataDic objectForKey:@"remark"] intValue];
            UIImage* tLStarImg = [UIImage imageNamed:@"star.png"];
            UIImage* tGStarImg = [UIImage imageNamed:@"star_gray.png"];
            for (int i=0; i<5; i++) {
                UIImageView* tStarImgView =[[UIImageView alloc] initWithFrame:CGRectMake(105+i*25, 336+8+tDesTextView.contentSize.height+8, 24, 24)];
                if (i<tStarNum) {
                    [tStarImgView setImage:tLStarImg];
                }else{
                    [tStarImgView setImage:tGStarImg];
                }
                [_ScrollView addSubview:tStarImgView];
                [tStarImgView release];
            }
            UIImageView* tRightArrImgView = [[UIImageView alloc] initWithFrame:CGRectMake(302, 336+8+tDesTextView.contentSize.height+15, 9, 13)];
            [tRightArrImgView setImage:[UIImage imageNamed:@"rarr.png"]];
            [_ScrollView addSubview:tRightArrImgView];
            [tRightArrImgView release];
            
            UIButton* tCommBtt = [UIButton buttonWithType:UIButtonTypeCustom];
            [tCommBtt addTarget:self action:@selector(toShowCommView) forControlEvents:UIControlEventTouchUpInside];
            tCommBtt.frame =CGRectMake(0, 336+8+tDesTextView.contentSize.height, 320, 44);
            [_ScrollView addSubview:tCommBtt];
            
            int tMaxH =336+8+tDesTextView.contentSize.height+44;
            if (tMaxH <= _ScrollView.frame.size.height) {
                tMaxH =_ScrollView.frame.size.height+1;
            }
            [_ScrollView setContentSize:CGSizeMake(320, tMaxH)];
        }else{
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:YES delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}
#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}
@end
